<template>
	<el-button type="primary" @click="show = true"
		><el-icon><Plus /></el-icon>选择商品</el-button
	>
	<el-drawer v-model="show" title="请选择库存" size="50%">
		<el-form :inline="true" :model="formData" class="demo-form-inline">
			<el-form-item>
				<el-input
					v-model="formData.productName"
					placeholder="请输入关键字"
				/>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="onQuery">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="success" @click="addProduct">添加</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="tableData" style="width: 100%" ref="productTableRef">
			<el-table-column
				type="selection"
				fixed
				prop="id"
				label="ID"
				width="80"
			/>
			<el-table-column prop="productName" label="商品名称" width="120" />
			<el-table-column prop="qty" label="库存数量" width="80" />
			<el-table-column label="存放地" width="120">
				<template #default="scope">
					<ShelfTree v-model="scope.row.shelfId"></ShelfTree>
				</template>
			</el-table-column>
			<el-table-column
				prop="productionDate"
				label="生产日期"
				width="120"
				:formatter="formatter"
			/>
			<el-table-column
				prop="expirationDate"
				label="过期日期"
				width="120"
				:formatter="formatter"
			/>
		</el-table>
		<br />
		<el-pagination
			background
			layout="prev, pager, next"
			:total="pageData.total"
			:page-size="pageData.pageSize"
			@current-change="pageChange"
		/>
	</el-drawer>
</template>

<script lang="ts" setup>
	import { inventoryApi } from '@/api';
	import { ref, onMounted, reactive } from 'vue';
	import ShelfTree from '@/components/ShelfTree.vue';
	import dayjs from 'dayjs';
	const tableData = ref([]);
	const productTableRef = ref();
	const show = ref(false);
	const props = defineProps({ List: { type: Array, default: [] } });
	const emits = defineEmits(['update:List']);

	const formData = reactive({
		productName: '',
	});

	const pageData = reactive({
		total: 0,
		pageSize: 3,
		pageNum: 1,
	});

	onMounted(() => {
		callInventoryApi();
	});
	const addProduct = () => {
		const rows = productTableRef.value.getSelectionRows();
		emits('update:List', rows);
		show.value = false;
	};

	const callInventoryApi = () => {
		let pageNum = pageData.pageNum;
		let pageSize = pageData.pageSize;
		inventoryApi.select
			.call({
				...formData,
				pageNum,
				pageSize,
			})
			.then((res: any) => {
				if (res.total > 0) {
					res.items.forEach((item: any) => {
						item.realQty = item.qty;
					});
				}
				pageData.total = res.total;
				tableData.value = res.items;
			});
	};
	const onQuery = () => {
		callInventoryApi();
	};

	const pageChange = (val: number) => {
		pageData.pageNum = val;
		callInventoryApi();
	};
	const formatter = (row, column, cellValue, index) => {
		return dayjs(cellValue).format('YYYY-MM-DD');
	};
</script>